﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace KindleComic
{
    public abstract class ComicSource
    {
        protected readonly HttpClient _client = new HttpClient(new HttpClientHandler()
        {
            AutomaticDecompression = DecompressionMethods.GZip,
            ClientCertificateOptions = ClientCertificateOption.Automatic
        });
        public string ComicSourceName { get; set; }
        public string ComicSourceUrl { get; set; }
        public string BasePath { get; set; } = @"D:\";
        public ComicSource()
        {
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
        }

        /// <summary>
        /// 获取html网页
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task<string> GetHtmlAsync(string url)
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
            request.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36");
            request.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            var response = await _client.SendAsync(request).ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            }
            return null;
        }
        /// <summary>
        /// 获取html网页
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string GetHtml(string url)
        {
            return GetHtmlAsync(url).Result;
        }

        /// <summary>
        /// 获取json数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task<string> GetJsonAsync(string url)
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
            request.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36");
            request.Headers.Add("Accept", "application/json");
            var response = await _client.SendAsync(request).ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            }
            return null;
        }
        /// <summary>
        /// 获取json数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string GetJson(string url)
        {
            return GetJsonAsync(url).Result;
        }
        /// <summary>
        /// 获取图片文件流
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task<Stream> GetPicStreamAsync(string url)
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
            request.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36");
            request.Headers.Add("Accept", "image/*");
            var response = await _client.SendAsync(request).ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
            }
            return null;
        }
        /// <summary>
        /// 获取图片文件流
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public Stream GetPicStream(string url)
        {
            return GetPicStreamAsync(url).Result;
        }


        /// <summary>
        /// 获取搜索列表页数据
        /// </summary>
        /// <param name="key">搜索词</param>
        /// <param name="page">页数</param>
        /// <returns></returns>
        public abstract Task<Tuple<List<ComicInfo>, int>> GetSearchListAsync(string key, int page);

        /// <summary>
        /// 获取搜索列表页数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public abstract Task<List<ComicInfo>> GetSearchListAsync(string key);


        /// <summary>
        /// 获取章节
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public abstract Task<List<ComicChapter>> GetComicChapterAsync(string url);

        /// <summary>
        /// 获取章节
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public List<ComicChapter> GetComicChapter(string url)
        {
            return GetComicChapterAsync(url).Result;
        }

        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public virtual async Task DownloadAsync(string url, string path)
        {
            var stream = await GetPicStreamAsync(url).ConfigureAwait(false);
            string imgPath = Path.Combine(BasePath, path);
            if (!Directory.Exists(Path.GetDirectoryName(imgPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(imgPath));
            }
            var image = System.Drawing.Image.FromStream(stream);
            image.Save(imgPath);
        }

        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public virtual void Download(string url, string path)
        {
            var stream = GetPicStreamAsync(url).Result;
            string imgPath = Path.Combine(BasePath, path);
            if (!Directory.Exists(Path.GetDirectoryName(imgPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(imgPath));
            }
            var image = System.Drawing.Image.FromStream(stream);
            image.Save(imgPath);
        }

        /// <summary>
        /// 获取图片地址
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public abstract Task<Dictionary<int, string>> GetComicImagesAsync(string url);
        /// <summary>
        /// 获取图片地址
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public Dictionary<int, string> GetComicImages(string url)
        {
            return GetComicImagesAsync(url).Result;
        }
    }
}
